<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{$route.query.id?'试题修改':'试题录入'}}</span>
      </div>
      <div class="main">
        <el-form
          ref="topicAddFrom"
          :model="topicAddFrom"
          :rules="rulesFrom"
          label-width="80px"
        >
        <!-- 学科 -->
          <el-form-item label="学科" prop="subjectID">
            <el-select
              style="width: 400px"
              v-model="topicAddFrom.subjectID"
              placeholder="请选择"
              @change="subjectChange"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录" prop="catalogID">
            <el-select
              v-model="topicAddFrom.catalogID"
              style="width: 400px"
              placeholder="请选择"
            >
              <!-- <el-option label="区域一" value="shanghai"></el-option> -->
              <el-option
                v-for="item in directorys"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业" prop="enterpriseID">
            <el-select
              v-model="topicAddFrom.enterpriseID"
              style="width: 400px"
              placeholder="请选择"
            >
              <el-option
                v-for="item in companyLists"
                :key="item.id"
                :label="item.company"
                :value="item.creatorID"
              ></el-option>
            </el-select>
          </el-form-item>
          <!--城市 -->
          <el-form-item label="城市" prop="province">
            <el-select
              style="width: 200px"
              v-model="topicAddFrom.province"
              placeholder="请选择"
              @change="citysChange"
            >
              <el-option
                v-for="item in city"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
              <!-- <el-option label="区域二" value="beijing"></el-option> -->
            </el-select>
            <!-- &nbsp -->
            <el-select
              v-model="topicAddFrom.city"
              placeholder="请选择"
              style="width: 200px"
            >
              <el-option
                v-for="item in region"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
<!-- 方向 -->
          <el-form-item label="方向" prop="direction">
            <el-select
              v-model="topicAddFrom.direction"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="item in direction"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- questionType, // 题型
      difficultys// 难度 -->
          <el-form-item label="题型" prop="questionType">
            <el-radio-group v-model="topicAddFrom.questionType" @change="changeRadio({})">
              <el-radio
                v-for="item in questionType"
                :key="item.id"
                :label="item.value + ''"
                :value="item.label + ''"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度" prop="difficulty">
            <el-radio-group v-model="topicAddFrom.difficulty">
              <el-radio
                v-for="item in difficultys"
                :key="item.id"
                :label="item.value + ''"
                :value="item.label + ''"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干" prop="question">
            <quill-editor
              v-model="topicAddFrom.question"
              :options="editorOptions"
            ></quill-editor>
          </el-form-item>
          <!-- 选项 -->
          <el-form-item
            label="选项："
            prop="options"
            v-if="topicAddFrom.questionType !== '3'"
          >
            <div
              class="option_item"
              v-for="item in topicAddFrom.options"
              :key="item.code"
            >
              <el-radio
              @change="changeRadio(item)"
                v-if="topicAddFrom.questionType === '1'"
                v-model="item.isRight"
                style="margin-right: 0"
                :label="true"
                >{{ item.code }}：</el-radio
              >
              <el-checkbox
                v-else
                v-model="item.isRight"
                style="margin-right: 0"
                :label="true"
                >{{ item.code }}：</el-checkbox
              >
              <el-input v-model="item.title" style="width: 240px"></el-input>
                 <el-upload
              style="margin-left:4px"
              action='#'
               :http-request="(obj)=>{request(item,obj)}"
              class="avatar-uploader"
               :headers="{'Authorization':'Bearer '+ token}"
              :on-success="(res,file)=>{uploadSuccess(item,res,file)}"
              :show-file-list="false">
              <img v-if="item.img" width="100%" :src="item.img" class="avatar">
              <span v-else>上传图片</span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
            </div>
            <!-- 添加按钮 -->
            <el-button
              type="danger"
              :disabled="topicAddFrom.questionType !== '2'"
              size="small"
              @click="addClick"
              >+增加选项与答案</el-button
            >
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频" prop="videoURL">
            <el-input
              v-model="topicAddFrom.videoURL"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <!-- 富文本框 -->
          <el-form-item label="答案解析" prop="answer">
            <quill-editor
              v-model="topicAddFrom.answer"
              :options="editorOptions"
            ></quill-editor>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注" prop="remarks">
            <el-input
              type="textarea"
              v-model="topicAddFrom.remarks"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <!--  试题标签-->
          <el-form-item label="试题标签" prop="tags">
            <el-select
            multiple
            filterable
            allow-create
            default-first-option
              v-model="topicAddFrom.tags"
              style="width: 400px"
              placeholder="请选择试题标签"
            >
              <!-- <el-option label="区域一" value="shanghai"></el-option> -->
              <el-option
                v-for="item in itemsTab"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-if="!$route.query.id"  type="primary" @click="questionsAdd">确认提交</el-button>
            <el-button v-else type="success" @click="clickSubmit" >确认修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
// import hljs from 'highlight.js' // 代码高亮

// 获取简单

// 获取方向

import {
  direction,
  questionType,
  difficulty as difficultys
} from '../../api/hmmm/constants'
import { provinces, citys } from '../../api/hmmm/citys'
import { simple } from '../../api/hmmm/subjects'
import { simple as dirSimple } from '../../api/hmmm/directorys' // 获取目录
import { list as companyList } from '../../api/hmmm/companys' // 获取企业
import { add, detail, update } from '../../api/hmmm/questions' // 添加  获取
import { simple as getTag } from '../../api/hmmm/tags' // 获取标签

// 代码高亮
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'

// 处理字母
import { getToken } from '@/utils/auth'
let index = 1 // 获取token
export default {
  name: 'Questions',
  data () {
    return {
      token: getToken(),
      topicAddFrom: {
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterpriseID: null, // 企业
        province: null, // 城市
        city: null, // 地区 5
        direction: null, // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: null, // 题干5
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        answer: '', // 答案解析
        remarks: null, // 题目备注
        tags: [] // 试题标签
      },
      videoURL: '', // 解析视频
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          // 语法高亮
          syntax: {
            highlight: (text) => hljs.highlightAuto(text).value
          }
        }
      },
      checkList: [],
      // 校验
      rulesFrom: {
        subjectID: [
          { required: true, trigger: ['change', 'blur'], message: '请选择学科' }
        ],
        catalogID: [
          { required: true, trigger: ['change', 'blur'], message: '请选择目录' }
        ],
        enterpriseID: [
          { required: true, trigger: ['change', 'blur'], message: '请选择企业' }
        ],
        province: [
          { required: true, trigger: ['change', 'blur'], message: '请选择城市' }
        ],
        direction: [
          { required: true, trigger: ['change', 'blur'], message: '请选择方向' }
        ],
        questionType: [{ required: true, trigger: ['change', 'blur'] }],
        difficulty: [{ required: true, trigger: ['change', 'blur'] }],
        question: [
          { required: true, trigger: ['change', 'blur'], message: '请输入题干' }
        ],
        answer: [
          { required: true, trigger: ['change', 'blur'], message: '请输入题干' }
        ]
      },
      subjectList: [], // 学科列表
      directorys: [], // 目录列表
      direction, // 获取方向
      city: provinces(), // 获取城市
      region: [],
      companyLists: [], // 企业列表
      itemsTab: [], // 试题列表
      questionType, // 题型
      difficultys // 难度
    }
  },
  created () {
    this.getSimpleList()
    this.getCompanyList() // 获取企业列表
    if (this.$route.query.id) { // 判断是否有id
      this.getQuestion()
    }
  },
  methods: {
    // 获取题目信息
    async getQuestion () {
      const { data } = await detail({ id: this.$route.query.id })
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.topicAddFrom = data
      const res = await dirSimple({ subjectID: this.topicAddFrom.subjectID })
      this.directorys = res.data // 目录
      const res2 = await getTag({ subjectID: this.topicAddFrom.subjectID })
      this.itemsTab = res2.data // tab标签
      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },
    // TODO tags
    // 获取学科列表
    async getSimpleList () {
      const { data } = await simple()
      this.subjectList = data
      // console.log(res)
    },
    // 获取目录
    async subjectChange () {
      this.topicAddFrom.catalogID = ''
      const { data } = await dirSimple({
        subjectID: this.topicAddFrom.subjectID
      })
      this.directorys = data
      // 获取试题标签
      const res = await getTag({ subjectID: this.topicAddFrom.subjectID })
      this.itemsTab = res.data
    },
    // 城市发生改变
    citysChange () {
      this.topicAddFrom.city = ''
      this.region = citys(this.topicAddFrom.province)
    },
    // 获取企业列表
    async getCompanyList () {
      const {
        data: { items }
      } = await companyList()
      this.companyLists = items
    },
    // 添加多选
    addClick () {
      const option = String.fromCharCode('D'.charCodeAt(0) + index++)
      this.topicAddFrom.options.push({
        isRight: false,
        code: option,
        title: '',
        img: ''
      })
    },
    // 选择单选框
    changeRadio (item) {
      console.log(item)
      // 1. 清除所有的选中
      this.topicAddFrom.options.forEach(item => {
        item.isRight = false
      })
      // 2. 自己选中
      item.isRight = true
    },
    // 试题添加
    questionsAdd () {
      console.log(this.$refs.topicAddFrom)
      this.$refs.topicAddFrom.validate(async (flag) => {
        if (!flag) return this.$message.error('验证失败')
        const data = { ...this.topicAddFrom }

        data.tags = data.tags.join(',')
        const res = await add(data)
        console.log(res)
        this.$message.success('添加成功')
        this.$router.push('/questions/list')
      })
    },
    // 试题修改
    // 修改
    async clickSubmit () {
      this.$refs.topicAddFrom.validate(async flag => {
        if (!flag) return this.$message.error('验证失败')
        const data = { ...this.topicAddFrom }
        data.tags = data.tags.join(',')
        const res = await update(data)
        console.log(res)
        this.$message.success('修改完成')
        this.$router.push('/questions/choice')
      })
    },
    uploadSuccess (item, res, file) {
      console.log(item, res, file)
      // res 是相应对象
      // file 选择后的文件对象   file.raw 原始文件对象
      // URL.createObjectURL(file.raw)  本地预览地址
      // item 就是当前的选项对象
      item.img = URL.createObjectURL(file.raw)
    },
    request (item, obj) {
      item.img = URL.createObjectURL(obj.file)
    }
  },
  // todo
  watch: {
    '$route.query': function () {
      if (this.$route.query.id) {
        this.getQuestion()
      } else {
        this.topicAddFrom = {
          subjectID: null, // 学科
          catalogID: null, // 目录
          enterpriseID: null, // 企业
          province: null, // 城市
          city: null, // 地区
          direction: null, // 方向
          questionType: '1', // 题型
          difficulty: '1', // 题干
          question: null, // 题干
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ]
        }
        this.$nextTick(() => {
          this.$refs.topicAddFrom.clearValidate()
        })
      }
    }
  }
}
</script>

<style scoped  lang='scss'>
.container {
  padding: 20px 20px;
}
.avatar-uploader {
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
}
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader i {
  position: absolute;
  right: 0;
  top: 0;
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.option_item {
  padding-bottom: 20px;
}
/* 修改富文本 */
 ::v-deep{
.ql-toolbar.ql-snow + .ql-container.ql-snow{
  height: 200px;
}
 }
</style>
